<template>
	<view class="container">
		<view v-for="item in list">
			<uni-row style="margin-bottom: 10px;" :gutter="20">
				<uni-col v-if="item.isMe" :span="2"><view class="demo-uni-col dark"><img src="@/static/avatar.jpg" style="width: 100%;border-radius: 50%;"></view></uni-col>
				<uni-col v-if="!item.isMe" :span="2"><view class="demo-uni-col dark"><img src="@/static/gpt.jpg" style="width: 100%;border-radius: 50%;"></view></uni-col>
				<uni-col :span="21"><view class="demo-uni-col light">{{item.content}}</view></uni-col>
			</uni-row>
		</view>
		
		<view>
			<textarea ref="inputText" style="background-color: gray;border-radius: 5%;" v-model="textdata" placeholder="请输入记录内容..."></textarea>
			<button v-on:click="send">发送</button>
		</view>
	</view>
</template>

<script>
	export default {
		name:"chat",
		onLoad: function (option) { //option为object类型，会序列化上个页面传递的参数
			console.log(option.key); //打印出上个页面传递的参数。
			this.key = option.key;
		},
		data() {
			return {
				href: '',
				key:'',
				textdata:"",
				list: [{
					isMe:false,
					content:"您好，有什么需要帮忙的吗？"
				}]
				
			}
		},
		methods: {
			send(){
				var text = this.textdata;
				var sendText = {isMe:true,content:this.textdata};
				this.list.push(sendText);
				let temp = {isMe:false,content:'请等待生成答案！'};
				this.list.push(temp);
				this.textdata = '';
				uni.request({
				    url: 'https://api.openai.com/v1/chat/completions', //仅为示例，并非真实接口地址。
					method:'POST',
				    data: {
				        model :"gpt-3.5-turbo",
						messages: [{"role": "user", "content": text}]
				    },
				    header: {
				        'Content-Type': 'application/json',
						'Authorization': 'Bearer '+this.key,
				    },
				    success: (res) => {
						var ans = res.data.choices[0].message.content;
				        temp.content=ans;
						this.list.push({});
						this.list.pop();
				    },fail: () => {
				    	temp.content=网络错误请重试;
						this.list.push({});
						this.list.pop();
				    }
				});
			}
		}
	}
</script>

<style>
	
</style>
